package com.vitabuybuy.tv.ui.auth

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.RegexUtils
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityBindEmailBinding
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.base.appContext
import com.library.common.ext.logE
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.toast.XToast
import com.library.common.net.HeadInterceptor
import com.vitabuybuy.tv.ui.MainActivity
import com.vitabuybuy.tv.ui.auth.viewmodel.AuthViewModel
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.BuildConfig
import com.vitabuybuy.tv.ui.tencent.liveroom.IMLVBLiveRoomListener
import com.vitabuybuy.tv.ui.tencent.liveroom.MLVBLiveRoom
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.LoginInfo

import kotlinx.android.synthetic.main.activity_bind_email.*

class BindEmailActivity : BaseActivity<AuthViewModel, ActivityBindEmailBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_bind_email

    private var from: String? = ""
    private var countryCode: String? = ""
    private var phone: String? = ""
    private var password: String? = ""
    private var avatar: String? = ""
    private var nickname: String? = ""
    private var gender: String? = ""
    private var birthday: String? = ""
    private var regionId: Int? = -1
    private var isGetCode = false

    override fun onGetBundle(bundle: Bundle?) {
        from = bundle?.getString("from")
        when (from) {
            FROM_REGISTER -> {
                countryCode = bundle?.getString("countryCode")
                phone = bundle?.getString("phone")
                password = bundle?.getString("password")
                avatar = bundle?.getString("avatar")
                nickname = bundle?.getString("nickname")
                gender = bundle?.getString("gender")
                birthday = bundle?.getString("birthday")
                regionId = bundle?.getInt("regionId")
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        when (from) {
            FROM_REGISTER -> {
                setTitle(getString(R.string.bind_email_1))
                mTvRight.apply {
                    text = getString(R.string.skip)
                    visibility = View.VISIBLE
                    setOnClickListener {
                        viewModel.register(
                            countryCode,
                            phone,
                            password,
                            nickname,
                            avatar,
                            "",
                            gender,
                            birthday,
                            regionId
                        );
                    }
                }
            }
            FROM_EMAIL_FORGET_PWD -> {
                setTitle(getString(R.string.find_password))
                btnFinish.text = getString(R.string.next_step)
            }
            FROM_BIND_EMAIL -> {
                setTitle(getString(R.string.bind_new_email))
            }
        }
    }


    override fun observeData() {
        viewModel.tokenInfo.observe(this, Observer {
            HeadInterceptor.sessionId = it.token
            mmkv.encode(MMKVContancts.USER_PHONE, it.phone.split("-")[1])
            mmkv.encode(MMKVContancts.SESSIONID, it.token)
            mmkv.encode(MMKVContancts.IS_LOGIN_IN, true)
            viewModel.getUserInfo()
        })
        viewModel.userInfoDto.observe(this, Observer {
            val loginInfo = LoginInfo().apply {
                sdkAppID = BuildConfig.LIVEAPPID.toLong()
                userID = it.id.toString()
                userSig = it.userSign
                userName = it.nickname
                userAvatar = it.avatar
            }
            MLVBLiveRoom.sharedInstance(appContext)
                .login(loginInfo, object : IMLVBLiveRoomListener.LoginCallback {
                    override fun onSuccess() {
                        mmkv.encode(MMKVContancts.SESSIONID, HeadInterceptor.sessionId)
                        mmkv.encode(MMKVContancts.IS_LOGIN_IN, true)
                        mmkv.encode(MMKVContancts.USER_EMAIL, it.email)
                        mmkv.encode(MMKVContancts.USER_ID, it.id)
                        mmkv.encode(MMKVContancts.USER_SIGN, it.userSign)
                        mmkv.encode(MMKVContancts.USER_AVATAR, it.avatar)
                        mmkv.encode(MMKVContancts.USER_NICKNAME, it.nickname)
                        MainActivity.openActivity(mContext)
                        RegisterSuccessActivity.openActivity(mContext)
                    }

                    override fun onError(errCode: Int, errInfo: String?) {
                        errInfo?.run {
                            errCode.logE("JIA--errCode--")
                            this.logE("JIA--errInfo--")
                            XToast.error("直播登录失败，请联系管理员")
                        }
                    }
                })
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(tvGetCode, btnFinish) { v ->
            when (v) {
                tvGetCode -> {
                    if (etEmail.text.isEmpty()) {
                        XToast.normal(getString(R.string.enter_email))
                        return@setOnclickNoRepeat
                    }
                    if (!RegexUtils.isEmail(etEmail.text)) {
                        XToast.normal(getString(R.string.please_enter_correct_email))
                        return@setOnclickNoRepeat
                    }
                    viewModel.sendToEmail(etEmail.text.toString())
                }
                btnFinish -> {
                    if (!isGetCode) {
                        XToast.normal(getString(R.string.please_get_code))
                        return@setOnclickNoRepeat
                    }
                    if (etCode.text.isEmpty()) {
                        XToast.normal(getString(R.string.enter_code))
                        return@setOnclickNoRepeat
                    }
                    when (from) {
                        FROM_REGISTER, FROM_EMAIL_FORGET_PWD, FROM_BIND_EMAIL -> {
                            viewModel.validateByEmail(
                                etEmail.text.toString(),
                                etCode.text.toString()
                            )
                        }
                    }
                }
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        super.handleEvent(msg)
        when (msg.code) {
            4 -> {
                XToast.success(getString(R.string.already_sms_code))
                timer.start()
            }
            5 -> {
                when (from) {
                    FROM_EMAIL_FORGET_PWD -> {
                        ChangePasswordActivity.openActivity(
                            mContext,
                            etEmail.text.toString(),
                            null,
                            ChangePasswordActivity.EMAIL_RESET
                        )
                    }
                    FROM_REGISTER -> {
                        viewModel.register(
                            countryCode,
                            phone,
                            password,
                            nickname,
                            avatar,
                            etEmail.text.toString(),
                            gender,
                            birthday,
                            regionId
                        )
                    }
                    FROM_BIND_EMAIL -> {
                        viewModel.resetUserInfo("email", etEmail.text.toString())
                    }
                }
            }
            10 -> {
                XToast.success(getString(R.string.update_success))
                finish()
            }
        }
    }

    private val timer = object : CountDownTimer((60 * 1000).toLong(), 1000) {
        override fun onTick(millisUntilFinished: Long) {
            isGetCode = true
            mBinding.tvGetCode.text = String.format(
                getString(R.string.get_sms_code_s),
                millisUntilFinished / 1000
            )
            mBinding.tvGetCode.isEnabled = false
        }

        override fun onFinish() {
            mBinding.tvGetCode.text = getString(R.string.get_sms_code)
            mBinding.tvGetCode.isEnabled = true
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 1001) {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timer.cancel()
    }

    companion object {
        const val FROM_REGISTER = "from_register"
        const val FROM_EMAIL_FORGET_PWD = "from_email_forget_pwd"
        const val FROM_BIND_EMAIL = "from_bind_email"
        fun openActivity(mContext: BaseActivity<*, *>, bundle: Bundle) {
            mContext.startActivity(bundle, BindEmailActivity::class.java)
        }
    }
}
